<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-form-item label="部门" prop="deptId">
                <treeselect
                    v-model="queryParams.deptId"
                    :options="deptOptions"
                    :show-count="true"
                    placeholder="请选择部门"
                    @keyup.enter.native="handleQuery"
                    style="width: 215px"
                />
            </el-form-item>
            <el-form-item label="员工状态" prop="staffType">
                <el-select
                    v-model="queryParams.staffType"
                    placeholder="请选择员工状态"
                    clearable
                >
                    <el-option
                        v-for="dict in dict.type.hrm_staff_type"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="员工姓名" prop="realName">
                <el-input
                    v-model="queryParams.realName"
                    placeholder="请输入员工姓名"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="工号" prop="staffNum">
                <el-input
                    v-model="queryParams.staffNum"
                    placeholder="请输入工号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>

            <el-form-item label="奖励级别" prop="jlLevel">
                <el-select
                    v-model="queryParams.jlLevel"
                    placeholder="请选择奖励级别"
                    @keyup.enter.native="handleQuery"
                    clearable
                >
                    <el-option
                        v-for="item in jlLevelList"
                        :key="item.jlLevel"
                        :label="item.jlLevel"
                        :value="item.jlLevel"
                    >
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="奖励时间" prop="daterange">
                <el-date-picker
                    v-model="timeArr"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    @change="setChangeDate($event, 'startDate', 'endDate')"
                >
                </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >查询</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <TableCard>
            <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                    <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        @click="handleAdd"
                        v-hasPermi="['hrm:reward:add']"
                        >奖励登记</el-button
                    >
                </el-col>
                <!-- <el-col :span="1.5">
                    <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['hrm:reward:edit']"
                        >修改</el-button
                    >
                </el-col>
                <el-col :span="1.5">
                    <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['hrm:reward:remove']"
                        >删除</el-button
                    >
                </el-col> -->
                <el-col :span="1.5">
                    <el-button
                        type="warning"
                        plain
                        icon="el-icon-download"
                        size="mini"
                        @click="handleExport"
                        v-hasPermi="['hrm:reward:export']"
                        >导出</el-button
                    >
                </el-col>
            </el-row>

            <el-table
                :border="Global.tableShowBorder"
                v-loading="loading"
                :data="rewardList"
                @selection-change="handleSelectionChange"
            >
                <!-- <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" /> -->
                <el-table-column label="序号" type="index" />
                <el-table-column
                    label="姓名(工号)"
                    align="center"
                    prop="realName"
                >
                    <template slot-scope="scope">
                        <span>{{
                            scope.row.realName + "(" + scope.row.staffNum + ")"
                        }}</span>
                    </template>
                </el-table-column>

                <el-table-column
                    label="当前员工状态"
                    align="center"
                    prop="staffTypeName"
                />

                <el-table-column label="部门" align="center" prop="deptName" />

                <el-table-column label="岗位" align="center" prop="postName" />

                <el-table-column
                    label="奖励名称"
                    align="center"
                    prop="jlName"
                />
                <el-table-column
                    label="奖励级别"
                    align="center"
                    prop="jlLevel"
                />
                <el-table-column
                    label="奖励时间"
                    align="center"
                    prop="jlDate"
                    width="180"
                >
                    <template slot-scope="scope">
                        <span>{{
                            parseTime(scope.row.jlDate, "{y}-{m}-{d}")
                        }}</span>
                    </template>
                </el-table-column>

                <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                >
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['hrm:reward:edit']"
                            >修改</el-button
                        >
                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handleDetail(scope.row)"
                            >查看</el-button
                        >

                        <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['hrm:reward:remove']"
                            >删除</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
            />
        </TableCard>

        <!-- 添加或修改奖励对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="1000px"
            append-to-body
        >
            <TableCard>
                <el-form
                    ref="form"
                    :model="form"
                    :rules="rules"
                    label-width="120px"
                >
                    <el-row>
                        <el-divider content-position="center"
                            >员工信息</el-divider
                        >
                        <el-col :span="12">
                            <el-form-item label="用户" prop="realName">
                                <el-input
                                    :disabled="form.id != null"
                                    suffix-icon="el-icon-search"
                                    readonly
                                    @focus="openSecelctOneUser"
                                    v-model="form.realName"
                                    placeholder="请选择用户"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="工号" prop="staffNum">
                                <el-input
                                    disabled
                                    v-model="form.staffNum"
                                    placeholder=""
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="部门" disabled prop="deptId">
                                <treeselect
                                    disabled
                                    v-model="form.deptId"
                                    :options="deptOptions"
                                    :show-count="true"
                                    placeholder=""
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="岗位" prop="postId">
                                <el-select
                                    disabled
                                    v-model="form.postId"
                                    placeholder=""
                                    clearable
                                    @change="setPostId"
                                >
                                    <el-option
                                        v-for="item in postList"
                                        :key="item.postId"
                                        :label="item.postName"
                                        :value="item.postId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-divider content-position="center"
                            >奖励信息</el-divider
                        >

                        <el-col :span="12">
                            <el-form-item label="奖励级别" prop="jlLevel">
                                <el-select
                                    :disabled="readonly"
                                    v-model="form.jlLevel"
                                    placeholder="请选择奖励级别"
                                    clearable
                                >
                                    <el-option
                                        v-for="item in $store.getters
                                            .allDefectObj['HR-WEB-130'] == 0 &&
                                        !form.id
                                            ? jlLevelList2
                                            : jlLevelList"
                                        :key="item.jlLevel"
                                        :label="item.jlLevel"
                                        :value="item.jlLevel"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="奖励名称" prop="jlName">
                                <el-input
                                    :disabled="readonly"
                                    v-model="form.jlName"
                                    placeholder="请输入奖励名称"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item
                                label="奖励时间"
                                prop="jlDate"
                                :rules="
                                    $store.getters.allDefectObj['HR-WEB-129'] ==
                                        0 && !form.id
                                        ? [
                                              {
                                                  pattern:
                                                      /^(\d{4})-(\d{1,2})-(\d{1,2})$/,
                                                  message:
                                                      '日期格式为yyyy-MM-dd',

                                                  trigger: 'blur',
                                              },
                                          ]
                                        : [
                                              {
                                                  required: true,
                                                  message: '请选择奖励时间',
                                                  trigger: 'blur',
                                              },
                                          ]
                                "
                            >
                                <el-input
                                    v-if="
                                        $store.getters.allDefectObj[
                                            'HR-WEB-129'
                                        ] == 0 && !form.id
                                    "
                                    v-model="form.jlDate"
                                    :disabled="readonly"
                                ></el-input>
                                <el-date-picker
                                    v-else
                                    :disabled="readonly"
                                    v-model="form.jlDate"
                                    placeholder="请选择奖励时间"
                                    type="date"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item
                                label="发奖单位"
                                prop="jlUtil"
                                :rules="
                                    $store.getters.allDefectObj['HR-WEB-132'] ==
                                        0 && !form.id
                                        ? [
                                              {
                                                  max: 30,
                                                  message:
                                                      '发奖单位长度不能超过 30 个字符',
                                              },
                                          ]
                                        : [
                                              {
                                                  required: true,
                                                  message: '请输入发奖单位',
                                                  trigger: 'blur',
                                              },
                                              {
                                                  max: 30,
                                                  message:
                                                      '发奖单位长度不能超过 30 个字符',
                                              },
                                          ]
                                "
                            >
                                <el-input
                                    :disabled="readonly"
                                    v-model="form.jlUtil"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :span="24">
                            <el-form-item label="描述" prop="describe">
                                <el-input
                                    :disabled="readonly"
                                    type="textarea"
                                    :rows="5"
                                    v-model="form.describe"
                                    placeholder=""
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </TableCard>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="!readonly" @click="submitForm"
                    >保 存</el-button
                >
                <el-button @click="cancel">{{
                    readonly ? "返 回" : "取 消"
                }}</el-button>
            </div>
        </el-dialog>
        <userTableDialog
            title="员工列表"
            :defaultParams="defaultParams"
            :open.sync="showUserTableVision"
            @confirm="setBaseInfo"
        >
        </userTableDialog>
    </div>
</template>

<script>
import {
    listReward,
    getReward,
    delReward,
    addReward,
    updateReward,
} from "@/api/hrm/reward";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listPostAll } from "@/api/system/post";

export default {
    name: "Reward",
    dicts: ["hrm_staff_type"],
    data() {
        return {
         
            showUserTableVision: false,
            timeArr: [],

            //部门
            // 职位选项
            postList: [],
            // 部门树选项
            deptOptions: [],
            deptOptionsArray: null,
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示查询条件
            showSearch: true,
            // 总条数
            total: 0,
            // 奖励表格数据
            rewardList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                // orderByColumn: "createTime",
                staffType: null,
                isAsc: "descending",
                realName: null,
                userId: null,
                staffNum: null,
                deptId: null,
                deptName: null,
                orgId: null,
                postId: null,
                postName: null,
                jlLevel: null,
                jlName: null,
                jlDate: null,
                jlUtil: null,
                describe: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                realName: [
                    {
                        required: true,
                        message: "请输入用户名",
                        trigger: "chenge",
                    },
                ],
                //奖励级别必填
                jlLevel: [
                    {
                        required: true,
                        message: "请选择奖励级别",
                        trigger: "blur",
                    },
                ],
                jlName: [
                    {
                        required: true,
                        message: "请输入奖励名称",
                        trigger: "blur",
                    },
                    { max: 30, message: "长度不超过30个字符", trigger: "blur" },
                ],
                jlDate: [
                    {
                        required: true,
                        message: "请选择奖励时间",
                        trigger: "blur",
                    },
                    //校验输入的时间为 yyyy-MM-dd格式
                ],
                jlUtil: [
                    {
                        required: true,
                        message: "请输入奖励单位",
                        trigger: "blur",
                    },
                ],
                describe: [
                    {
                        max: 200,
                        message: "长度不超过200个字符",
                        trigger: "blur",
                    },
                ],
            },

            jlLevelList: [
                {
                    jlLevel: "国家级",
                },
                {
                    jlLevel: "市级",
                },
                {
                    jlLevel: "集团级",
                },
            ],
            jlLevelList2: [
                {
                    jlLevel: "一级",
                },
                {
                    jlLevel: "二级",
                },
                {
                    jlLevel: "三级",
                },
            ],
            defaultParams: {
                isLink: true,
                // 匹配在职员工
                staffTypes: "1,4,5,6",
            },
            readonly: false,
        };
    },
    components: { Treeselect },
    created() {
        this.getList();
        this.getTreeselect();
        this.getPostList();
    },
    methods: {
        setChangeDate(item, startDate, endDate) {
            console.log(item, "时间段");
            if (item.length > 0) {
                this.queryParams.startDate = item[0];
                this.queryParams.endDate = item[1];
            } else {
                this.queryParams.startDate = null;
                this.queryParams.endDate = null;
            }
        },
        //唤醒员工弹窗
        openSecelctOneUser() {
            this.showUserTableVision = true;
        },

        // 设置选中的基础信息
        setBaseInfo(row) {
            this.form.userId = row.userId;
            this.form.realName = row.realName;
            this.form.staffNum = row.staffNum;
            this.form.deptId = row.deptId;
            this.form.orgId = row.orgId;
            this.form.staffType = row.staffType;
            if (row.postId) {
                let temp = row.postId.split(",");
                if (temp.length > 0) {
                    this.form.postId = Number(temp[0]);
                }
            }
            this.form.deptName = this.parseSelectTree(this.form.deptId);
            this.form.postName = this.parsePostName(this.form.postId);
        },
        parsePostName(ids) {
            if (!ids) {
                return "—";
            }
            if (ids != null && ids != "") {
                let obj = this.postList.find((item) => item.postId == ids);
                if (obj) {
                    return obj.postName;
                }
            }
            return "—";
        },
        getUserList() {
            listInduction({ deptId: this.form.deptId }).then((response) => {
                this.recordList = response.data;
            });
        },
        getPostList() {
            listPostAll().then((res) => {
                this.postList = res.data;
            });
        },

        /** 查询部门下拉树结构 */
        getTreeselect() {
            treeselect().then((response) => {
                this.deptOptions = response.data;
                this.deptOptionsArray = this.flattenArray(this.deptOptions);
            });
        },
        flattenArray(arr) {
            let result = [];
            for (let i = 0; i < arr.length; i++) {
                let item = arr[i];
                result.push(item);
                if (item.children) {
                    result = result.concat(this.flattenArray(item.children));
                }
            }
            return result;
        },
        parseSelectTree(id) {
            console.log(this.deptOptionsArray, "this.deptOptionsArray");
            let tempObj = this.deptOptionsArray.find((item) => item.id == id);
            if (tempObj) {
                return tempObj.label;
            }
            return "—";
        },
        /** 查询奖励列表 */
        getList() {
            this.loading = true;
            listReward(this.queryParams).then((response) => {
                this.rewardList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.readonly = false;
            this.form = {
                id: null,
                realName: null,
                userId: null,
                staffNum: null,
                deptId: null,
                deptName: null,
                orgId: null,
                postId: null,
                postName: null,
                jlLevel: null,
                jlName: null,
                jlDate: null,
                jlUtil: null,
                describe: null,
            };
            this.resetForm("form");
        },
        /** 查询按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.timeArr = [];
            this.queryParams.startDate = null;
            this.queryParams.endDate = null;

            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "奖励登记";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids;
            getReward(id).then((response) => {
                this.form = response.data;
                this.form.postId = Number(this.form.postId);
                this.open = true;
                this.title = "修改奖励信息";
            });
        },
        handleDetail(row) {
            this.reset();
            const id = row.id || this.ids;
            getReward(id).then((response) => {
                this.form = response.data;
                this.form.postId = Number(this.form.postId);
                this.open = true;
                this.readonly = true;
                this.title = "查看奖励信息";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    if (this.form.id != null) {
                        updateReward(this.form).then((response) => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        if (
                            this.$store.getters.allDefectObj["HR-WEB-131"] == 0
                        ) {
                            this.open = false;
                            return;
                        }
                        addReward(this.form).then((response) => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal
                .confirm("确定要删除该奖励记录吗？")
                .then(function () {
                    return delReward(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => {});
        },
        /** 导出按钮操作 */
        handleExport() {
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, "0");
            const day = String(date.getDate()).padStart(2, "0");
            this.download(
                "hrm/reward/export",
                {
                    ...this.queryParams,
                },
                `员工奖励信息_${year}年${month}月${day}日.xlsx`
            );
        },
    },
};
</script>
